#import "Core.h"

@implementation PrayAlarmNavigationController

- (id)initWithRootViewController:(PrayViewController *)rootViewController
{
	if ( (self = [super init]) != nil ) {
		_rootViewController = rootViewController;
		self.title = @"스케쥴";
		self.viewControllers = [NSArray arrayWithObjects:[[PrayAlarmViewController alloc] initWithRootViewController:_rootViewController], nil];
		self.navigationBar.tintColor = [UIColor colorWithRed:87.0f/255.0f green:77.0f/255.0f blue:78.0f/255.0f alpha:1.0f];
	}
	
	return self;
}

@end


@interface PrayAlarmViewController (private)

- (void)addEvent;

@end

@implementation PrayAlarmViewController (private)

- (void)addEvent
{
	// When add button is pushed, create an EKEventEditViewController to display the event.
	EKEventEditViewController *addController = [[EKEventEditViewController alloc] initWithNibName:nil bundle:nil];
	
	// set the addController's event store to the current event store.
	addController.eventStore = self.eventStore;
	
	// load setting data
	PraySettingData* currentSetting = [PraySettingData getSettingDataFromDefaultPath];
	
	// event customizing.
	EKEvent* event = [EKEvent eventWithEventStore:addController.eventStore];
	event.startDate = self.selectedDate;
	
	if( currentSetting.enableLightMystery )
		event.endDate = [NSDate dateWithTimeInterval:60*60*24*55 sinceDate:event.startDate];
	else
		event.endDate = [NSDate dateWithTimeInterval:60*60*24*53 sinceDate:event.startDate];
	
	EKRecurrenceRule*	recurRule = [[EKRecurrenceRule alloc] initRecurrenceWithFrequency:EKRecurrenceFrequencyDaily 
																			   interval:1 
																					end:[EKRecurrenceEnd recurrenceEndWithEndDate:event.endDate]];
	event.recurrenceRule = recurRule;
	event.alarms = [NSArray arrayWithObject:[EKAlarm alarmWithRelativeOffset:0]];
	event.title = @"9일기도 바칠 시간입니다.";
	
	// set customized event
	addController.event = event;
	
	// present EventsAddViewController as a modal view controller
	[_rootViewController presentModalViewController:addController animated:YES];
	
	addController.editViewDelegate = self;
	[addController release];
}

@end

@implementation PrayAlarmViewController

@synthesize rootViewController = _rootViewController;
@synthesize eventStore = _eventStore;
@synthesize defaultCalendar = _defaultCalendar;
@synthesize eventsList = _eventsList;

- (id)initWithRootViewController:(PrayViewController*)rootViewController
{
	if( (self = [super init]) != nil )
	{
		_rootViewController = rootViewController;

		// Initialize an event store object with the init method. Initilize the array for events.
		self.eventStore = [[EKEventStore alloc] init];
		
		self.eventsList = [[NSMutableArray alloc] initWithArray:0];
		
		// Get the default calendar from store.
		self.defaultCalendar = [self.eventStore defaultCalendarForNewEvents];

	}
	
	return self;
}

- (void)viewDidLoad
{
	[super viewDidLoad];
	
	self.title = @"스케쥴";
	self.delegate = self;
	self.dataSource = self;
	self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addEvent)];
	
	[self reloadData];
}

#pragma mark -
#pragma mark EKEventEditViewDelegate

// Overriding EKEventEditViewDelegate method to update event store according to user actions.
- (void)eventEditViewController:(EKEventEditViewController *)controller 
		  didCompleteWithAction:(EKEventEditViewAction)action {
	
	NSError *error = nil;
	EKEvent *thisEvent = controller.event;
	
	PraySettingData*	settingData = [PraySettingData getSettingDataFromDefaultPath];
	
	switch (action) {
		case EKEventEditViewActionCanceled:
			// Edit action canceled, do nothing. 
			break;
			
		case EKEventEditViewActionSaved:
			// When user hit "Done" button, save the newly created event to the event store, 
			// and reload table view.
			// If the new event is being added to the default calendar, then update its 
			// eventsList.
			if (self.defaultCalendar ==  thisEvent.calendar) {
				[self.eventsList addObject:thisEvent];
			}
			
			[controller.eventStore saveEvent:controller.event span:EKSpanThisEvent error:&error];
			settingData.startDate = thisEvent.startDate;
			settingData.endDate = thisEvent.endDate;
//			[self.tableView reloadData];
			break;
			
		case EKEventEditViewActionDeleted:
			// When deleting an event, remove the event from the event store, 
			// and reload table view.
			// If deleting an event from the currenly default calendar, then update its 
			// eventsList.
			if (self.defaultCalendar ==  thisEvent.calendar) {
				[self.eventsList removeObject:thisEvent];
			}
			
			[controller.eventStore removeEvent:thisEvent span:EKSpanThisEvent error:&error];
			settingData.startDate = nil;
			settingData.endDate = nil;
//			[self.tableView reloadData];
			break;
			
		default:
			break;
	}
	
	[PraySettingData saveSettingDataToDefaultPath:settingData];
	
	// Dismiss the modal view controller
	[controller dismissModalViewControllerAnimated:YES];
	[self reloadData];

}


// Set the calendar edited by EKEventEditViewController to our chosen calendar - the default calendar.
- (EKCalendar *)eventEditViewControllerDefaultCalendarForNewEvents:(EKEventEditViewController *)controller {
	EKCalendar *calendarForEdit = self.defaultCalendar;
	return calendarForEdit;
}

#pragma mark -
#pragma mark KalDataSource

- (void)presentingDatesFrom:(NSDate *)fromDate to:(NSDate *)toDate delegate:(id<KalDataSourceCallbacks>)delegate
{
	[self loadedDataSource:self];
}

- (NSArray *)markedDatesFrom:(NSDate *)fromDate to:(NSDate *)toDate
{
	PraySettingData*	settingData 	= [PraySettingData getSettingDataFromDefaultPath];
	NSDate*				startDate 		= settingData.startDate;
	NSDate*				endDate 		= settingData.endDate;
	
	NSDate*				dateCursor 		= [fromDate laterDate:startDate];
	NSDate*				dateBoundary 	= [toDate earlierDate:endDate];
	NSMutableArray*		resultArray 	= [[NSMutableArray alloc] init];
	
	if( startDate == nil || endDate == nil )
		return nil;
	else if( [toDate compare:startDate] == NSOrderedAscending )
		return nil;
	else if( [fromDate compare:endDate] == NSOrderedDescending )
		return nil;
	
	while ( [dateCursor compare:dateBoundary] != NSOrderedDescending ) {
		[resultArray addObject:dateCursor];
		[dateCursor release];
		dateCursor = [[resultArray objectAtIndex:[resultArray count] -1] dateByAddingTimeInterval:60*60*24];
	}
	
	[settingData release];
	
	return resultArray;
}

- (void)loadItemsFromDate:(NSDate *)fromDate toDate:(NSDate *)toDate
{
	
}

- (void)removeAllItems
{
	
}

#pragma mark -
#pragma mark UITableViewDataSource

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
	[tableView deselectRowAtIndexPath:indexPath animated:YES];	
}

#pragma mark -
#pragma mark UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	return 1;
}

// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	UITableViewCell* 	cell 		= [[UITableViewCell alloc] init];
	PraySettingData* 	settingData = [PraySettingData getSettingDataFromDefaultPath];
	NSTimeInterval 		interval;
	NSInteger			nOfDay;
	
	if( settingData.startDate == nil || settingData.endDate == nil )
	{
		cell.textLabel.font = [UIFont fontWithName:@"NanumGothic" size:PRAY_DEFAULT_FONT_SIZE];
		cell.textLabel.text = @"+ 버튼을 눌러 9일기도를 시작해주세요";
		return cell;
	}
	
	if( [self.selectedDate compare:settingData.startDate] != NSOrderedAscending && [self.selectedDate compare:settingData.endDate] != NSOrderedDescending )
	{
		interval 	= [self.selectedDate timeIntervalSinceDate:settingData.startDate];
		nOfDay 		= (NSInteger)(interval / (24 * 60 * 60));
		
		if( settingData.enableLightMystery )
		{
			switch (nOfDay % 4) {
				case 0:
					cell.textLabel.text = @"환희의 신비";
					break;
				case 1:
					cell.textLabel.text = @"빛의 신비";
					break;
				case 2:
					cell.textLabel.text = @"고통의 신비";
					break;
				case 3:
					cell.textLabel.text = @"영광의 신비";
					break;
			}
		}
		else
		{
			switch (nOfDay % 3) {
				case 0:
					cell.textLabel.text = @"환희의 신비";
					break;
				case 1:
					cell.textLabel.text = @"고통의 신비";
					break;
				case 2:
					cell.textLabel.text = @"영광의 신비";
					break;
			}
		}
	}
	
	return cell;
}


@end